package com.example.demo.jucConcurrent.Exchanger详解;

import java.util.concurrent.Exchanger;
import java.util.concurrent.TimeUnit;

/**
 * 来一个非常简单的并发问题,你有连个相同的数据buffer,一个或者多个数据生成者,和一个
 * 或者多个数据的消费者,只是Exchange类只能同步2个线程,所以你只能在你的生产者和消费者问题中只要有一个生产者和一个消费者
 * 时使用这个类
 */
public class Test {

    static  class  Producer extends  Thread{
        private Exchanger<Integer> exchanger;
        private  static  int data = 0;

        public Producer(String name,Exchanger<Integer> exchanger) {
            this.exchanger = exchanger;
        }

        @Override
        public void run() {
            for (int i = 0; i <5 ; i++) {
                try {
                    TimeUnit.SECONDS.sleep(1);
                    data = i;
                    System.out.println(getName()+"交换前"+data);
                    data = exchanger.exchange(data);
                    System.out.println(getName()+"交换后"+data);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    static  class  Consumer extends  Thread{

        private  Exchanger<Integer> exchanger;
        private  static  int data = 0;

        public Consumer(String name,Exchanger<Integer> exchanger) {
            this.exchanger = exchanger;
        }

        @Override
        public void run() {
            while (true){
                data = 0;
                System.out.println(getName()+"交换前"+data);
                try {
                    TimeUnit.SECONDS.sleep(1);
                    data = exchanger.exchange(data);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                System.out.println(getName()+"交换后"+data);
            }
        }
    }


    public static void main(String[] args) throws InterruptedException {
        Exchanger<Integer> exchanger = new Exchanger<>();
        new Producer("", exchanger).start();
        new Consumer("",exchanger).start();
        TimeUnit.SECONDS.sleep(7);
        System.exit(-1);
    }
}
